package xyz.canran.project.algorithm.zerocopy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 *
 * @author canran
 */
public class TranslateToZeroCopy {

    private static final Logger log = LoggerFactory.getLogger(TranslateToZeroCopy.class);

    public void zeroCopyConsole(String fileName) {

        try (WritableByteChannel writableByteChannel = Channels.newChannel(System.out);
              FileInputStream fis = new FileInputStream(fileName)) {
            FileChannel channel = fis.getChannel();
            // 通过FileChannel的transferTo()方法将文件数据传输到System.out通道
            channel.transferTo(0, channel.size(), writableByteChannel);
        } catch (IOException e) {
            log.error("file not find", e);
        }

    }

    public void zeroCopyFile(String sourceFileName, String targetFileName) {

        File sourceFile = new File(sourceFileName);
        if (!sourceFile.exists()) {
            log.error("source file does not exist");
            return;
        }
        long fileSize = sourceFile.length();

        try (FileOutputStream fos = new FileOutputStream(targetFileName, true);
             FileInputStream fis = new FileInputStream(sourceFileName)) {
            FileChannel fisChannel = fis.getChannel();
            FileChannel fosChannel = fos.getChannel();
            // 将文件复制到另一个文件
            fosChannel.transferFrom(fisChannel, 0, fileSize);
        } catch (IOException e) {
            log.error("file not find", e);
        }
    }
}
